package com.baturu.vin.benz.transformer;

import com.baturu.vin.benz.consts.BenzConstant;
import com.baturu.vin.benz.dto.*;
import com.baturu.vin.benz.service.impl.util.BenzI18nService;
import com.baturu.vin.dto.EPCPartsImageDTO;
import com.baturu.vin.dto.EPCPartsImagePositionDTO;
import com.baturu.vin.dto.superEPC.*;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * TransformerService
 * 类型转换Service
 *
 * @author majianming
 * @date 2019-04-18 13:53
 */
@Service
public class BenzGroupTransformerService {

    @Autowired
    private BenzI18nService benzI18nService;

    @Autowired
    private BenzDashBroadTransformerService dashBroadTransformerService;
    @Autowired
    private BenzAttributeTransformerService attributeTransformerService;


    /**
     * 将vin信息转换为车型信息
     *
     * @param benzVinFinInfoDTOS vin 信息
     * @return 超级epc车型信息
     */
    public Optional<SEPCCarTypeDTO> benzVinFinInfoDTOToSuperCarTypeDTO(List<BenzVinFinInfoDTO> benzVinFinInfoDTOS) {
        if (CollectionUtils.isEmpty(benzVinFinInfoDTOS)) {
            return Optional.empty();
        }
        List<String> vinCodes = benzVinFinInfoDTOS.stream().map(b -> {
            String whc = b.getWhc();
            String chassbm = b.getChassbm();
            String chassIdent = b.getChassIdent();
            return whc + chassbm + chassIdent;
        }).collect(Collectors.toList());

        return Optional.of(
                SEPCCarTypeDTO
                        .builder()
                        .extendAttrDTOs(
//                                和前端约定key是vinList
                                Lists.newArrayList(SEPCExtendAttributeDTO.builder().code("vinList").value(vinCodes).desc("vin Codes").build())
                        ).build());

    }


    /**
     * 将奔驰车型信息转换为上传的车型信息
     *
     * @param superCarInfoDTO 奔驰超级epc车型信息
     * @return 超级epc车型信息
     */
    public Optional<SEPCCarTypeDTO> benzSuperCarInfoToSuperCarTypeDTO(BenzSuperCarInfoDTO superCarInfoDTO) {
        BenzSuperCarConfigurationDTO benzSuperCarConfigurationDTO;
        if (Objects.isNull(superCarInfoDTO) ||
                Objects.isNull((benzSuperCarConfigurationDTO = superCarInfoDTO.getBenzSuperCarConfigurationDTO()))) {
            return Optional.empty();
        }

//        下面这些为了配合上层接口
        List<SEPCCarTypeDetailDTO> carTypeDetailDTOList = Lists.newArrayListWithCapacity(3);

//      底盘信息
        carTypeDetailDTOList.addAll(dashBroadTransformerService.chassisDetailsTransform(benzSuperCarConfigurationDTO));

//        sa Code
        carTypeDetailDTOList.addAll(dashBroadTransformerService.saCodeTransform(benzSuperCarConfigurationDTO));


//        弹簧信息 弹簧可能不存在 那就不显示这个字段
        carTypeDetailDTOList.addAll(dashBroadTransformerService.springTransform(superCarInfoDTO.getBenzSpringsDTO()));


//        下面开始是真正需要返回的信息
        return Optional.of(SEPCCarTypeDTO.builder()
                .btrId(benzSuperCarConfigurationDTO.getBtrId())
                .vinCode(superCarInfoDTO.getVinCode())
                .showCarType(
                        benzSuperCarConfigurationDTO.getType()
                                + benzSuperCarConfigurationDTO.getSubModel1()
                                + " " + benzSuperCarConfigurationDTO.getSalesModel())
                .brandName(benzSuperCarConfigurationDTO.getBrandName())
                .country(benzSuperCarConfigurationDTO.getCountry())
                .engineType(benzSuperCarConfigurationDTO.getEngine())
                .transmissionType(benzSuperCarConfigurationDTO.getTransmission())
                .carTypeDetailDTOList(carTypeDetailDTOList).build());
    }


    public List<SEPCGroupDTO> benzSubGroupToGroupDTO(Collection<BenzSuperSubGroupDTO> benzSuperSubGroupDTOS, Collection<SEPCGroupDTO> mainGroups) {
        if (CollectionUtils.isEmpty(benzSuperSubGroupDTOS) || CollectionUtils.isEmpty(mainGroups)) {
            return Collections.emptyList();
        }
        Map<String, List<SEPCGroupDTO>> mainGroupMap = mainGroups.stream().collect(Collectors.groupingBy(SEPCGroupDTO::getMainGroupCode));

        return benzSuperSubGroupDTOS.stream().flatMap(
                s -> {
                    List<SEPCGroupDTO> mainGroupLists = mainGroupMap.get(s.getMainGroupNo());
                    if (CollectionUtils.isEmpty(mainGroupLists)) {
                        return Stream.empty();
                    }
                    List<EPCPartsImageDTO> epcPartsImageDTOS = toGroupImageExtends(s.getBenzImagesDTOS());
                    return mainGroupLists.stream().map(
                            m -> SEPCGroupDTO.builder()
                                    .parentGroup(m)
                                    .level(BenzConstant.SUPER_SUB_GROUP_LEVEL)
                                    .mainGroup(m.getMainGroup())
                                    .mainGroupCode(m.getMainGroupCode())
                                    .subGroup(s.getSubGroupNo() + " " + s.getDesc())
                                    .subGroupCode(s.getSubGroupNo())
                                    .extendAttrDTOs(attributeTransformerService.toBaseCode(s))
                                    .epcPartsImageDTOList(epcPartsImageDTOS)
                                    .build()
                    );
                }
        ).collect(Collectors.toList());


    }


    private List<EPCPartsImageDTO> toGroupImageExtends(List<BenzImagesDTO> benzImagesDTOS) {
        if (CollectionUtils.isEmpty(benzImagesDTOS)) {
            return Collections.emptyList();
        }
        return benzImagesDTOS.stream().map(b -> {
            EPCPartsImageDTO epcPartsImageDTO = new EPCPartsImageDTO();
            epcPartsImageDTO.setImageUrl(b.getImageUrl());
            epcPartsImageDTO.setImageCode(b.getImageCode());
//            List<BenzImagePositionDTO> imagePositions = b.getImagePositions();
//            List<EPCPartsImagePositionDTO> imagePositionDTOS = imagePositions.stream().map(
//                    i -> {
//                        EPCPartsImagePositionDTO epcPartsImagePositionDTO = new EPCPartsImagePositionDTO();
//                        epcPartsImagePositionDTO.setBottomRight(i.getBottomRight());
//                        epcPartsImagePositionDTO.setTopLeft(i.getTopLeft());
//                        epcPartsImagePositionDTO.setPosition(i.getPosition());
//                        return epcPartsImagePositionDTO;
//                    }
//            ).collect(Collectors.toList());
//            epcPartsImageDTO.setEpcPartsImagePositionDTOs(imagePositionDTOS);
            return epcPartsImageDTO;
        }).collect(Collectors.toList());
    }

    /**
     * 子组转换
     *
     * @param benzSuperSubGroupDTOS
     * @param mainGroupDTO
     * @return
     */
    public List<SEPCGroupDTO> benzSubGroupToGroupDTO(Collection<BenzSuperSubGroupDTO> benzSuperSubGroupDTOS, SEPCGroupDTO mainGroupDTO) {
        if (CollectionUtils.isEmpty(benzSuperSubGroupDTOS)) {
            return Collections.emptyList();
        }
        String mainGroupCode = null;
        String mainGroupName = null;
        if (Objects.nonNull(mainGroupDTO)) {
            mainGroupCode = mainGroupDTO.getMainGroupCode();
            mainGroupName = mainGroupDTO.getMainGroup();

        }
        final String mainGroupNameFinal = mainGroupName;
        final String mainGroupCodeFinal = mainGroupCode;


        return benzSuperSubGroupDTOS.stream().map(b -> {
            List<SEPCExtendAttributeDTO> extendAttrDTOs = Lists.newArrayList();
            extendAttrDTOs.addAll(attributeTransformerService.toBaseCode(b));
            List<EPCPartsImageDTO> epcPartsImageDTOS = toGroupImageExtends(b.getBenzImagesDTOS());
            return SEPCGroupDTO.builder()
                    .parentGroup(mainGroupDTO)
                    .subGroup(b.getSubGroupNo() + " " + b.getDesc())
                    .nextGroupCount(0)
                    .mainGroupCode(mainGroupCodeFinal)
                    .mainGroup(mainGroupNameFinal)
                    .subGroupCode(b.getSubGroupNo())
                    .extendAttrDTOs(extendAttrDTOs)
                    .epcPartsImageDTOList(epcPartsImageDTOS)
                    .imageUrl(b.getImagePath())
                    .level(BenzConstant.SUPER_SUB_GROUP_LEVEL)
                    .build();
        }).collect(Collectors.toList());
    }


    /**
     * 子组转换
     *
     * @param subGroupDTO
     * @param superCarInfoDTO
     * @return
     */
    public Optional<BenzSuperSubGroupDTO> groupDTOToSubGroupDTO(SEPCGroupDTO subGroupDTO, BenzSuperCarInfoDTO superCarInfoDTO) {
        if (Objects.isNull(subGroupDTO) || subGroupDTO.getLevel() != BenzConstant.SUPER_SUB_GROUP_LEVEL || Objects.isNull(superCarInfoDTO)) {
            return Optional.empty();
        }
        List<SEPCExtendAttributeDTO> extendAttrDTOs = subGroupDTO.getExtendAttrDTOs();
        String baseCode = attributeTransformerService.getBaseCode(extendAttrDTOs);
        return Optional.of(
                BenzSuperSubGroupDTO.builder()
                        .catNum(baseCode)
                        .mainGroupNo(subGroupDTO.getMainGroupCode())
                        .subGroupNo(subGroupDTO.getSubGroupCode())
                        .benzImagesDTOS(toBenzImagesDTO(subGroupDTO.getEpcPartsImageDTOList()))
                        .baseCode(baseCode)
                        .build());
    }

    private List<BenzImagesDTO> toBenzImagesDTO(List<EPCPartsImageDTO> epcPartsImageDTOList) {
        if (CollectionUtils.isEmpty(epcPartsImageDTOList)) {
            return Collections.emptyList();
        }
        return epcPartsImageDTOList.stream().map(i -> BenzImagesDTO.builder()
                .imageCode(i.getImageCode())
                .imageUrl(i.getImageUrl()).build()).collect(Collectors.toList());
    }

    /**
     * 配件转换
     *
     * @param benzSuperPartsInfoDTOS
     * @return
     */
    public List<SEPCPartsDTO> benzPartsInfoToPartsDTO(Collection<BenzSuperPartsInfoDTO> benzSuperPartsInfoDTOS) {
        return benzSuperPartsInfoDTOS.stream().map(l -> {
                    List<EPCPartsImagePositionDTO> epcPartsImagePositions = l.getEpcPartsImagePositions();

                    EPCPartsImageDTO epcPartsImageDTO = new EPCPartsImageDTO();
                    epcPartsImageDTO.setImageUrl(l.getImagePath());
                    epcPartsImageDTO.setImageCode(l.getImageCode());
                    epcPartsImageDTO.setEpcPartsImagePositionDTOs(epcPartsImagePositions);

                    List<String> descs = Lists.newArrayList();
                    if (StringUtils.isNotBlank(l.getDesc())) {
                        //添加备注
                        if (StringUtils.isNotBlank(l.getNeutral())) {
                            descs.add(StringUtils.trimToEmpty(l.getDesc()) + StringUtils.trimToEmpty(l.getNeutral()));
                        } else {
                            descs.add(l.getDesc());
                        }
                    }
                    if (StringUtils.isNotBlank(l.getRepPartNo()) && (StringUtils.isNotBlank(l.getRepType()))) {
                        //替换编码
                        String replacedByText = benzI18nService.trans("replaced_by");
                        descs.add(replacedByText + StringUtils.trimToEmpty(l.getRepType()) + StringUtils.trimToEmpty(l.getRepPartNo()) + StringUtils.trimToEmpty(l.getEs2Code()));

                        if (StringUtils.isNotBlank(l.getRepPart())) {
                            //+ xxx
                            descs.add(" + " + StringUtils.trimToEmpty(l.getRepPart()));
                        }

                    }
                    if (StringUtils.isNotBlank(l.getSaCode())) {
                        //添加sa 码
                        String codeAsText = benzI18nService.trans("code_as");
                        descs.add(codeAsText + l.getSaCode());
                    }
                    if (StringUtils.isNotBlank(l.getOptPart())) {
                        //可共用 编码
                        String optionalWithText = benzI18nService.trans("optional_with");
                        descs.add(optionalWithText + l.getOptPart());
                    }

                    return SEPCPartsDTO.builder()

                            .partsCode(StringUtils.trimToEmpty(l.getPartType()) + StringUtils.trimToEmpty(l.getPartNum()) + StringUtils.trimToEmpty(l.getEs2Code()))
                            .installNum(l.getQty())
                            .callout(l.getCallout())
//                            如果是 1 ,表示总成 在名称前面带上  •
                            .epcName((StringUtils.equals(l.getIndent(), "1") ? " • " : "") + l.getNounName())
                            .epcDesc(String.join("<br/>", descs))
                            .btrPartsName(l.getBtrPartsName())
                            .epcPartsImageDTOs(Lists.newArrayList(epcPartsImageDTO))
                            .imageUrl(l.getImagePath())

                            .build();
                }

        ).collect(Collectors.toList());

    }

    /**
     * 奔驰特有的主组dto  转换为 group
     *
     * @param benzSuperMainGroupDTOS
     * @return
     */
    public List<SEPCGroupDTO> benzMainGroupToMainGroup(List<BenzSuperMainGroupDTO> benzSuperMainGroupDTOS) {
        if (CollectionUtils.isEmpty(benzSuperMainGroupDTOS)) {
            return Collections.emptyList();
        }

        return benzSuperMainGroupDTOS.stream().map(b -> {

            List<SEPCExtendAttributeDTO> attributeDTOS = Lists.newArrayList();
            attributeDTOS.addAll(attributeTransformerService.toAttribute(b.getSubMainGroupDTOS()));
            attributeDTOS.addAll(attributeTransformerService.toBaseCode(b));
            return SEPCGroupDTO.builder()
                    .mainGroup(b.getShowName())
                    .nextGroupCount(BooleanUtils.isTrue(b.getHasNext()) ? 1 : 0)
                    .mainGroupCode(b.getGroupNo())
                    .level(BenzConstant.SUPER_MAIN_GROUP_LEVEL)
                    .extendAttrDTOs(attributeDTOS)
                    .build();
        }).collect(Collectors.toList());
    }


    /**
     * group 转换为奔驰特有的主组dto
     *
     * @param groupDTO 主组dto
     * @return 奔驰特有的主组dto
     */
    public BenzSuperMainGroupDTO mainGroupToBenzMainGroup(SEPCGroupDTO groupDTO) {
        if (Objects.isNull(groupDTO) || groupDTO.getLevel() != BenzConstant.SUPER_MAIN_GROUP_LEVEL) {
            return null;
        }
        List<SEPCExtendAttributeDTO> extendAttrDTOs = groupDTO.getExtendAttrDTOs();

        String baseCode = attributeTransformerService.getBaseCode(extendAttrDTOs);
        return BenzSuperMainGroupDTO.builder().groupNo(groupDTO.getMainGroupCode()).baseCode(baseCode).build();
    }
}
